package org.framework.common.api.entity;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;

import org.framework.common.api.query.Criterion.Operator;
import org.framework.common.api.support.model.PageModel;
import org.framework.common.api.support.model.ProcessModel;
import org.framework.common.api.support.model.QueryModel;
import org.framework.common.ext.util.StringUtil;
import org.hibernate.annotations.GenericGenerator;

import com.fasterxml.jackson.annotation.JsonIgnore;

@MappedSuperclass
public abstract class CommonEntityUUID implements CommonEntityAware<String> {

	/** serialVersionUID(long):. */
	private static final long serialVersionUID = 6868718716266032062L;

	@Id
	@GeneratedValue(generator = "UUIDHexGenerator")
	@GenericGenerator(name = "UUIDHexGenerator", strategy = "uuid.hex")
	@Column(name = "id", length = 50, nullable = false)
	protected String id;

	// 状态标识
	@Column(name = "status", length = 10, nullable = true)
	protected String status;
		
	// 删除标识（F=有效的<未删除>、T=无效的<已删除>）
	@Column(name = "invalid", length = 10, nullable = true)
	protected String invalid;
	
	// 分页
	@Transient @JsonIgnore
	protected String limit;
	
	// 分页
	@Transient @JsonIgnore
	protected String offset;
	
	/**
	 * @see org.framework.common.api.entity.CommonEntityAware#save(org.framework.common.api.service.bo.CommonBoAware, org.springframework.jdbc.core.JdbcTemplate, java.lang.String[])
	 * @author chanlong(陈龙)
	 * @date 2016年8月30日 下午12:36:01
	 */
	@Override
	public Object save(final String... options) throws Exception {
		return result(RETURN_SUCCESS, "记录保存成功！", ProcessModel.factory().bo.update(this));
	}
	
	/**
	 * @see org.framework.common.api.entity.CommonEntityAware#save(org.framework.common.api.service.bo.CommonBoAware, org.springframework.jdbc.core.JdbcTemplate, java.util.Map)
	 * @author chanlong(陈龙)
	 * @date 2016年8月30日 下午4:56:37
	 */
	@Override
	public Object save(final Map<String, Object> params) throws Exception {
		return result(RETURN_SUCCESS, "记录保存成功！", ProcessModel.factory().bo.update(this));
	}

	/**
	 * @see org.framework.common.api.entity.CommonEntityAware#delete(org.framework.common.api.service.bo.CommonBoAware, org.springframework.jdbc.core.JdbcTemplate, java.lang.String[])
	 * @author chanlong(陈龙)
	 * @date 2016年8月30日 下午12:36:06
	 */
	@Override
	public Object delete(final String... options) throws Exception {
		ProcessModel.factory().bo.delete(this); return result(RETURN_SUCCESS, "所选记录已删除！", null);
	}
	
	/**
	 * @see org.framework.common.api.entity.CommonEntityAware#loader(org.framework.common.api.service.bo.CommonBoAware, org.springframework.jdbc.core.JdbcTemplate, org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor, java.lang.String[])
	 * @author chanlong(陈龙)
	 * @date 2016年9月1日 上午11:59:40
	 */
	@Override
	public Object loader(final String... options) throws Exception {
		return result(RETURN_SUCCESS, "已加载记录详情！", ProcessModel.factory().bo.loader(this));
	}
	
	/**
	 * @see org.framework.common.api.entity.CommonEntityAware#query(java.util.Map, java.lang.String[])
	 * @author chanlong(陈龙)
	 * @date 2016年9月6日 下午12:50:41
	 */
	@Override
	public Object query(final Map<String, Object> params, final String... options) throws Exception {
		// 创建查询模型
		QueryModel query = new QueryModel(this.getClass(), limit, offset);
		
		// 设置查询条件
		Set<Entry<String, Object>> entry = params.entrySet();
		for (Entry<String, Object> bean : entry) {
			Object value = bean.getValue();
			if(StringUtil.isNotEmpty(value)){
				processQuery(query, bean.getKey(), value);
			}else{
				return result(RETURN_INVALID, "设置查询参数有误！", "");
			}
		}
		
		// 设置排序方式
		Object order = params.get("order");
		if(StringUtil.isNotEmpty(order)){
			String[] orders = String.valueOf(order).split(",");
			for(String sort:orders){
				String[] sorts = sort.split(":");
				query.addOrder(sorts[0], "desc".equals(sorts[1]));
			}
		}
		
		// 执行查询操作
		PageModel<?> result = ProcessModel.factory().bo.findByQuery(query);
		
		// 返回查询结果
		return result(RETURN_SUCCESS, "已返回查询所得结果！", result);
	}
	
	/**
	 * 处理查询条件.
	 * @param query
	 * @param key
	 * @param value
	 * @author chanlong(陈龙)
	 * @date 2016年9月6日 上午11:06:43
	 */
	protected void processQuery(final QueryModel query, final String key, final Object value){
		switch (key) {
			case "order":
			case "limit":
			case "offset":
			break;
			default:
				query.addAndQuery(key, value, Operator.EQ);
			break;
		}
	}
	
	/**
	 * 返回接口调用结果.
	 * @param code
	 * @param message
	 * @param data
	 * @return
	 * @author chanlong(陈龙)
	 * @date 2016年8月30日 下午12:38:51
	 */
	protected Map<String, Object> result(final int code, final String message, final Object data){
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("resultCode", code);
		result.put("resultMessage", message);
		result.put("data", getResultData(null, data));
		return result;
	}
	
	/**
	 * 获取接口调用接口的数据内容.
	 * @param key
	 * @param value
	 * @return
	 * @author chanlong(陈龙)
	 * @date 2016年9月2日 上午11:36:58
	 */
	protected Object getResultData(final String key, final Object value){
		Map<String, Object> data = new HashMap<>();
		if(StringUtil.isEmpty(key) && StringUtil.isNotEmpty(value)){
			return value;
		}else if(StringUtil.isEmpty(value)){
			data.put("result", "empty");
		}else{
			data.put(key, value);
		}
		return data;
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getInvalid() {
		return invalid;
	}

	public void setInvalid(String invalid) {
		this.invalid = invalid;
	}

	public String getLimit() {
		return limit;
	}

	public void setLimit(String limit) {
		this.limit = limit;
	}

	public String getOffset() {
		return offset;
	}

	public void setOffset(String offset) {
		this.offset = offset;
	}
	
}
